<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <button>0</button>

    <button>1</button>
    <button>2</button>


</body>

<script>
    var but = document.getElementsByTagName('button');
    for (var i = 0; i < but.length; i++) {
        but[i].onclick = (function(index) {
            return function() {
                alert(index);
            }
        })(i);
    }
</script>

</html>